package com.bkitmobile.kesu.appengine.web.client.SupportPopup;


import java.util.*;

import com.bkitmobile.kesu.appengine.web.client.GreetingService;
import com.bkitmobile.kesu.appengine.web.client.GreetingServiceAsync;
import com.bkitmobile.kesu.appengine.web.client.KeSuServer;
import com.bkitmobile.kesu.appengine.web.client.entity.UserInfo;
import com.bkitmobile.kesu.appengine.web.client.utility.LoginPopupConstant;
import com.bkitmobile.kesu.appengine.web.client.utility.RegisterPopupConstant;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DatePicker;

public class RegisterPopup extends DialogBox {
	
	private HashMap<String, Widget> InputParam = 
		new HashMap<String, Widget> ();
	private final GreetingServiceAsync greetingService = GWT
		.create(GreetingService.class);
	private final FormPanel form = new FormPanel();
	
	///// Cac field bat buoc: username, pid, sex, email
	/// tra ve true neu 1 trong cac field bat buoc do trong
	private final boolean hasNullValue() {
		// TODO Auto-generated method stub
		TextBox username = (TextBox) this.InputParam.get(RegisterPopupConstant.userName);
		PasswordTextBox pid = (PasswordTextBox) this.InputParam.get(RegisterPopupConstant.pid);
		TextBox email = (TextBox) this.InputParam.get(RegisterPopupConstant.email);
		if (username.getText().isEmpty() || pid.getText().isEmpty() || email.getText().isEmpty())
			return true;
		else
			return false;
	}
	
	private boolean checkDate (int date, int month, int year)
	{
		switch (month)
		{
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			if (date <= 31 && date >0)
				return true;
			else 
				return false;
		case 4:
		case 6:
		case 9:
		case 11:
			if (date <= 30 && date >0)
				return true;
			else
				return false;
		case 2:
			if ((year%4==0 && year%100!=0) || year%400 == 0)
			{
				if (date <=28 && date >0)
					return true;
				else
					return false;
			}
			else
			{
				if (date <=27 && date >0)
					return true;
				else
					return false;
			}
		}
		return false;
	}
	
	private String getBdString (int date, int month, String year)
	{
		//DatePicker tmp = new DatePicker();
		if (checkDate(date,month,Integer.parseInt(year)))
			return Integer.toString(date) + "/" + Integer.toString(month)+"/"+year;
		else 
			return "";
	}
	
	private final boolean isMale()
	{
		String title = RegisterPopupConstant.sex + RegisterPopupConstant.male;
		RadioButton free = (RadioButton) InputParam.get(title);
		return free.isChecked();
	}
	
	private final boolean isFree()
	{
		String title = RegisterPopupConstant.usrKind + RegisterPopupConstant.free;
		RadioButton male = (RadioButton) InputParam.get(title);
		return male.isChecked();
	}
	
	private final UserInfo getInfo()
	{
		UserInfo usr = new UserInfo();
		TextBox usr_name = (TextBox) InputParam.get(RegisterPopupConstant.userName);
		usr.setUserName(usr_name.getText());
		PasswordTextBox pid = (PasswordTextBox) InputParam.get(RegisterPopupConstant.pid);
		PasswordTextBox confirm_pid = (PasswordTextBox) InputParam.get(RegisterPopupConstant.authen_pid);
		if (!pid.getText().equals(confirm_pid.getText()))
		{
			Window.alert("B\u1ea1n nh\u1eadp m\u1eadt kh\u1ea9u kh\u00f4ng \u0111\u00fang");
			return null;
		}
		
		TextBox email = (TextBox) InputParam.get(RegisterPopupConstant.email);
		String email_str = email.getText();
		if (email_str.split("@").length<2)
		{
			Window.alert("B\u1ea1n nh\u1eadp e-mail kh\u00f4ng \u0111\u00fang");
			return null;
		}
		usr.setEmail(email_str);
		usr.setPid(pid.getText());
		TextBox fName = (TextBox) InputParam.get(RegisterPopupConstant.fName);
		usr.setfName(fName.getText());
		TextBox lName = (TextBox) InputParam.get(RegisterPopupConstant.lName);
		usr.setlName(lName.getText());
		
		ListBox bday_date = (ListBox) InputParam.get(RegisterPopupConstant.bday+"date");
		ListBox bday_month = (ListBox) InputParam.get(RegisterPopupConstant.bday+"month");
		ListBox bday_year = (ListBox) InputParam.get(RegisterPopupConstant.bday+"year");
		//usr.setBday(bday.getText());
		String bday = this.getBdString(bday_date.getSelectedIndex()+1,bday_month.getSelectedIndex()+1,
				bday_year.getItemText(bday_year.getSelectedIndex()));
		if (bday.equals(""))
		{
			Window.alert("B\u1ea1n \u0111\u00e3 ch\u1ecdn ng\u00e0y sinh sai");
			return null;
		}
		
		usr.setBday(bday);
		usr.setSex(this.isMale());
		usr.setPremium(!this.isFree());
		
		return usr;
	}
	
	private HorizontalPanel createTextPanel (String title)
	{
		HorizontalPanel create = new HorizontalPanel();
		Label name = new Label();
		name.setText(title);
		name.setPixelSize(150, 20);
		create.add(name);
		
		TextBox input = new TextBox();
		input.setPixelSize(300, 20);
		create.add(input);
		InputParam.put(title, input);
		
		return create;
	}
	
	private HorizontalPanel createPasswordPanel (String title)
	{
		HorizontalPanel create = new HorizontalPanel();
		Label name = new Label();
		name.setText(title);
		name.setPixelSize(150, 20);
		create.add(name);
		
		PasswordTextBox input = new PasswordTextBox();
		input.setPixelSize(300, 20);
		create.add(input);
		InputParam.put(title, input);
		
		return create;
	}
	
	
	private HorizontalPanel createDatePanel (String title)
	{
		HorizontalPanel create = new HorizontalPanel();
		Label name = new Label();
		name.setText(title);
		name.setPixelSize(150, 20);
		create.add(name);
		int month_size = 125;
		int date_size = 50;
		int year_size = 60;
		
		Label tmp;
		
		/*PasswordTextBox input = new PasswordTextBox();
		input.setPixelSize(300, 20);
		create.add(input);
		InputParam.put(title, input);*/
		//// create date input
		ListBox date_info = new ListBox();
		create.add(date_info);
		date_info.setPixelSize(date_size, 20);
		for (int i = 1;i<=31;i++)
			date_info.addItem(Integer.toString(i));
		InputParam.put(title+"date", date_info);
		tmp = new Label();
		tmp.setPixelSize(15, 20);
		create.add(tmp);
		
		/////create month input
		ListBox month_info = new ListBox();
		create.add(month_info);
		month_info.setPixelSize(month_size, 20);
		for (String i:RegisterPopupConstant.month_const)
			month_info.addItem(i);
		InputParam.put(title+"month", month_info);
		tmp = new Label();
		tmp.setPixelSize(15, 20);
		create.add(tmp);
		
		
		///// create year input
		ListBox year_info = new ListBox();
		create.add(year_info);
		year_info.setPixelSize(year_size, 20);
		for (int i = 1900;i<2010;i++)
			year_info.addItem(Integer.toString(i));
		InputParam.put(title+"year", year_info);
		
		
		
		
		return create;
	}
	
	private HorizontalPanel createChoicePanel (String title,String[] choice)
	{
		HorizontalPanel create = new HorizontalPanel();
		Label name = new Label();
		name.setText(title);
		name.setPixelSize(150, 20);
		create.add(name);
		
		for (int i = 0; i<choice.length;i++)
		{
			RadioButton input = new RadioButton(title,choice[i]);
			input.setPixelSize(300/choice.length, 20);
			create.add(input);
			input.setChecked(true);
			InputParam.put(title + choice[i], input);
		}
		
		return create;
	}
	
	@SuppressWarnings("deprecation")
	public RegisterPopup()
	{
		//create the form panel, set its action and method
		form.setHeight("300px");
		form.setAction("/register");
		form.setMethod(FormPanel.METHOD_GET);
		//set the main widget for the panel to a vertical panel
		VerticalPanel panel = new VerticalPanel();
		panel.setSpacing(4);
		panel.add(createTextPanel(RegisterPopupConstant.userName));
		panel.add(createPasswordPanel(RegisterPopupConstant.pid));
		panel.add(createPasswordPanel(RegisterPopupConstant.authen_pid));
		panel.add(createTextPanel(RegisterPopupConstant.fName));
		panel.add(createTextPanel(RegisterPopupConstant.lName));
		panel.add(createDatePanel(RegisterPopupConstant.bday));
		
		panel.add(createTextPanel(RegisterPopupConstant.email));
		
		String [] sex = RegisterPopupConstant.sexes;
		panel.add(createChoicePanel(RegisterPopupConstant.sex, sex ));
		
		String [] specific_usr = RegisterPopupConstant.specific_usr;
		panel.add(createChoicePanel(RegisterPopupConstant.usrKind, specific_usr));
		
		Button cancel_btn = new Button();
		cancel_btn.addClickListener(new ClickListener() {
			
			@Override
			public void onClick(Widget sender) {
				// TODO Auto-generated method stub
				hide();
				////set Enable for login_btn and register_btn again
				RootPanel login_area = RootPanel.get("login_btn");
				ToggleButton login_btn = (ToggleButton)login_area.getWidget(0);
				login_btn.setEnabled(true);
				login_btn.setDown(true);
				RootPanel register_area = RootPanel.get("register_btn");
				ToggleButton reg_btn = (ToggleButton)register_area.getWidget(0);
				reg_btn.setEnabled(true);
				reg_btn.setDown(true);
			}
		});
		cancel_btn.setText("Tho\u00e1t");
		Button submit_btn = new Button();
		submit_btn.setText("\u0110\u0103ng k\u00fd");
		submit_btn.addClickListener(new ClickListener() {
			
			@Override
			public void onClick(Widget sender) {
				// TODO Auto-generated method stub
				if (hasNullValue())
				{
					Window.alert("B\u1ea1n ph\u1ea3i \u0111i\u1ec1n to\u00e0n " +
							"b\u1ed9 c\u00e1c \u00f4 tr\u1ed1ng b\u1eaft bu\u1ed9c");
				}
				else
				{
					UserInfo input = getInfo();
					if (input!=null)
					{
						greetingService.doRegister(input, new AsyncCallback<String>() {					
							@Override						
							public void onFailure(Throwable caught) {						
								// TODO Auto-generated method stub						
								Window.alert("T\u00e0i kho\u1ea3n n\u00e0y \u0111\u00e3 " +
										"c\u00f3 ng\u01b0\u1eddi s\u1eed d\u1ee5ng");
							}
							@Override
							public void onSuccess(String result) {
								// TODO Auto-generated method stub
								Window.Location.reload();
							}
						});
					}
				}
			}
		});
		
		//Add 2 button into form
		HorizontalPanel horizon = new HorizontalPanel();
		horizon.setSpacing(5);
		horizon.add(submit_btn);
		horizon.add(cancel_btn);
		
		panel.add(horizon);
		
		form.setWidget(panel);
		form.addFormHandler(new FormHandler() {
			public void onSubmitComplete(FormSubmitCompleteEvent event) 
			{
				//Window.alert(event.getResults());
				//form.setVisible(false);
				
				//form.getParent().setVisible(false);
				
			}
			public void onSubmit(FormSubmitEvent event) {
				if (hasNullValue()) {
					Window.alert(LoginPopupConstant.warning_text_after_submit);
					event.setCancelled(true);
				}
			}
			
		});
		
		this.setWidget(form);
		this.setText("Th\u00f4ng tin \u0111\u0103ng k\u00fd");
		// Enable animation.
		setAnimationEnabled(true);

		  
		// Enable glass background.
		setGlassEnabled(true);
		this.setPopupPosition(400, 50);
	}
}
